/* 
 * File:   unixsocket.cpp
 * Author: robbiediaz
 * 
 * Created on January 27, 2009, 5:29 PM
 */
#ifdef __APPLE__
#ifndef unix
#define unix 1
#endif
#endif

#ifdef linux
#ifndef unix
#define unix 1
#endif
#endif

#ifdef unix
#include "unixsocket.h"
#include <iostream>
#include <sstream>

#define BUFSIZE 100

unixSocket::unixSocket() {
    port = "5222";

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // fill in my IP for me

    getaddrinfo(NULL, port.c_str(), &hints, &res);

    sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    bind(sockfd, res->ai_addr, res->ai_addrlen);

    listen(sockfd, 10);
}

unixSocket::~unixSocket() {
    close(sockfd);
}

void unixSocket::sendString(std::string msg) {
    send(new_fd, msg.c_str(), msg.length(), 0);
}

std::string unixSocket::readString(Peer* p) {
    std::string s = "";
    char buffer[BUFSIZE];

    int numBytes;

    //    if ((numBytes = recv(p->getSockFd(), buffer, 99, 0) == -1)) {
    //        std::cout << "error" << std::endl;
    //        perror("recv");
    //    }

    do {
        numBytes = recv(p->getSockFd(), buffer, BUFSIZE - 1, 0);
        buffer[numBytes] = '\0';
        s += buffer;
        std::cout << "bytes: " << numBytes << std::endl;
    } while (numBytes == BUFSIZE - 1);

    return s;
}

Peer* unixSocket::acceptConnection() {
    addr_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *) & their_addr, &addr_size);

    Peer* p = new Peer;
    char ip[INET_ADDRSTRLEN];

    inet_ntop(their_addr.ss_family,
            &(((struct sockaddr_in*) (struct sockaddr *) & their_addr)->sin_addr),
            ip, INET_ADDRSTRLEN);
    p->setIpAddr(ip);
    p->setPort(((struct sockaddr_in*) (struct sockaddr *) & their_addr)->sin_port);
    p->setSockFd(new_fd);

    return p;
}

#endif